<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/31
 * 描述:
 */

namespace app\result\order;

use app\model\goods\Goods;
use app\model\order\Order;
use app\model\order\OrderExpress;
use app\model\order\OrderGoods;
use app\model\order\OrderRefund;
use app\model\user\User;
use app\result\BaseResult;
use app\result\UserMsgResult;
use app\service\CreditService;
use app\service\OrderService;
use think\facade\Db;

class OrderManagerResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Order();
    }


    public function list($args = []): array
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $status = trim($args['order_status'] ?? '');
        $type = trim($args['type'] ?? '');//all/need_send/need_check/need_receive/finished/distribution
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['order_id|order_sn|user_id', 'like', '%' . trim($args['keyword']) . '%'];
        }
        if (is_numeric($status)) {
            $where[] = ['order_status', '=', $status];
        }
        if ($type == 'need_send') {
            $where[] = ['order_status', '=', 1];
        } elseif ($type == 'need_check') {
            $where[] = ['order_status', '=', 7];
        } elseif ($type == 'need_receive') {
            $where[] = ['order_status', '=', 2];
        } elseif ($type == 'finished') {
            $where[] = ['order_status', 'in', '3,4'];
        } elseif ($type == 'refund') {
            $where[] = ['order_status', 'in', '5'];
        } elseif ($type == 'distribution') {
            //分销订单
            $where[] = ['parent_user_id', '>', 0];
        }
        if (!empty($args['created_time'])) {
            $where[] = ['created_at', 'between', [$args['created_time'][0], $args['created_time'][1]]];
        }
        if (!empty($args['pay_time'])) {
            $where[] = ['pay_time', 'between', [$args['pay_time'][0], $args['pay_time'][1]]];
        }
        $field = 'order_id,user_id,order_sn,parent_id,order_status,total_price,order_pay_price,pay_price,shipping_fee,pay_type,pay_status,coupon_price,pay_time,total_refund_price,remark,created_at,updated_at';
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, $field, 'order_id desc', $page, $pageSize)?->toArray();
        if ($data) {

            $users = (new User())->data_list_nopage(['user_id' => array_column($data, 'user_id')], 'user_id,username,account');
            $users = $users ? array_column($users, null, 'user_id') : [];
            $modelOrderGoods = new OrderGoods();
            foreach ($data as &$v) {
                $v['username'] = $users[$v['user_id']]['account'] ?? '';
                $v['order_status_desc'] = OrderResult::get_order_status_desc($v['order_status'], $v);
                $goodsList = $modelOrderGoods->data_list_nopage(['order_id' => $v['order_id']], 'goods_name,goods_image');
                $v['goods_name'] = '共' . count($goodsList) . '款商品';
                $v['pay_type_desc'] = OrderResult::get_pay_type_desc($v['pay_type']);
                $v['goods_images'] = array_column($goodsList, 'goods_image');
            }
            unset($v);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }

    public function get($args = []): array
    {
        $order_id = intval($args['order_id'] ?? 0);
        $data = $this->model->data_get(['order_id' => $order_id])?->toArray();
        if (!$data) {
            return $this->error_return('订单不存在');
        }
        $data['order_status_desc'] = OrderResult::get_order_status_desc($data['order_status'], $data);
        if ($data['address']) {
            $address = json_decode($data['address'], true);
            $data['address'] = $address;
            $data['address_info'] = $address['name'] . ' ' . $address['phone'] . ' ' . $address['province'] . $address['city'] . $address['area'] . $address['detail'];
        }
        if (in_array($data['order_status'], [2, 3, 4])) {
            $data['express_info'] = (new OrderExpress())->data_get(['order_id' => $order_id])?->toArray();
        }
        $data['buttons'] = $this->get_buttons($data);
        $goodsList = (new OrderGoods())->data_list_nopage(['order_id' => $order_id]);
        if ($data['order_status'] == 5) {
            $data['refund_log'] = (new OrderRefund())->data_get(['order_id' => $order_id], '*', 'id desc');
            if (!empty($data['refund_log']['images'])) {
                $data['refund_log']['images'] = explode(',', $data['refund_log']['images']);
            }
        }

        $data['pay_type_desc'] = OrderResult::get_pay_type_desc($data['pay_type']);
        if ($data['order_goods_type'] == 2 && empty($data['virtual_info'])) {
            //虚拟商品
            $data['virtual_info'] = (new Goods())->get_value(['goods_id' => $goodsList[0]['goods_id']], 'virtual_info');
        }
        $data['invoice'] = OrderResult::query_order_invoice($data['order_id']);

        return $this->success_return('success', [
            'order' => $data,
            'goods_list' => $goodsList
        ]);
    }

    public function get_buttons($order)
    {
        //订单状态：0=待支付，1=待发货，2=待收货，3=待评价，4=已完成，5=售后中，6=已取消，7=待审核
        $buttons = [
            'check' => 0,//审核
            'send' => 0,//发货
            'edit_price' => 0,//修改价格
            'refund' => 0,//退款
            'express' => 0,//查物流
        ];
        if ($order['order_status'] == 7) {
            $buttons['check'] = 1;
        }
        if ($order['pay_status'] == 0 && $order['order_status'] == 0) {
            $buttons['edit_price'] = 1;
        }
        if ($order['order_status'] == 1) {
            $buttons['send'] = 1;
        }
        if ($order['order_status'] == 5) {
            $buttons['refund'] = 1;
        }
        if ($order['order_status'] == 2 && $order['order_goods_type'] != 2) {
            $buttons['express'] = 1;
        }
        return $buttons;
    }

    public function del_data($args): array
    {
        $order_id = intval($args['order_id'] ?? 0);
        $model = new Order();
        $res = $model->data_update(['order_id' => $order_id], [
            'del_time' => time()
        ]);
        return $this->success_return('success');
    }

    //支付审核
    public function pay_check($args): array
    {
        $order_id = intval($args['order_id'] ?? 0);
        $status = $args['status'] ?? '';
        if (!in_array($status, ['1', '-1'])) {
            return $this->error_return('参数错误');
        }
        $order = $this->model->data_get(['order_id' => $order_id])?->toArray();
        if (!$order) {
            return $this->error_return('订单不存在');
        } elseif ($order['order_status'] != 7) {
            return $this->error_return('订单状态不支持审核');
        }
        if ($status == 1) {
            $upData = [
                'order_status' => 1,
                'pay_status' => 1,
                'pay_price' => $order['order_pay_price'],
                'pay_time' => $order['updated_at'],
                'check_time' => date('Y-m-d H:i:s')
            ];
        } else {
            $upData = [
                'order_status' => 0,
                'pay_status' => 0,
                'pay_price' => 0,
                'pay_time' => null,
                'pay_expire' => time() + 24 * 60 * 60,//24小时,驳回后恢复待支付
                'check_time' => date('Y-m-d H:i:s')
            ];
        }
        $res = (new Order())->data_update(['order_id' => $order_id], $upData);
        if ($res) {
            (new OrderResult())->add_order_log([
                'order_sn' => $order['order_sn'],
                'order_id' => $order['order_id'],
                'remark' => '审核支付状态：' . ($status == 1 ? '通过' : '驳回'),
            ]);
            if ($status == -1) {
                UserMsgResult::add($order['user_id'], [
                    'title' => '订单审核驳回',
                    'content' => '订单号：' . $order['order_sn'] . '，订单审核驳回',
                    'type' => 1,
                    'path_info' => [
                        'title' => '订单详情',
                        'path' => '/pages/packageA/order/detail?order_sn=' . $order['order_sn'],
                        'jump_type' => 'inner',//inner=内页，tab=底部导航，link=外链
                    ],
                ]);
            } else {
                $goodsList = (new OrderGoods())->data_list_nopage(['order_id' => $order_id]);
                //销量增加、库存减少
                foreach ($goodsList as $goods) {
                    (new Goods())->data_update(['goods_id' => $goods['goods_id']], [
                        'sales_num' => ['inc', $goods['goods_count']],
                        //'stock' => ['dec', $goods['goods_num']],
                    ]);
                }
                if (config('point.open') && config('point.order')) {
                    $point = config('point.order');//1元1积分转换
                    $point = $order['order_pay_price'] * $point;
                    if ($point >= 1) {
                        $pointAction = (new CreditService())->point_action($order['user_id'], $point, [
                            'order_sn' => $order['order_sn'],
                            'remark' => '订单支付赠送'
                        ]);
                    }

                }
            }
            return $this->success_return('审核成功');
        }
        return $this->error_return('审核失败');
    }

    public function edit_price($args)
    {
        $order_id = intval($args['order_id'] ?? 0);
        $order = $this->model->data_get(['order_id' => $order_id], 'user_id,order_id,order_sn,order_status,order_pay_price')?->toArray();
        if (!$order) {
            return self::error_return('订单不存在');
        } elseif ($order['order_status'] != 0) {
            return self::error_return('订单状态不支持修改价格');
        }
        $price = floatval($args['price'] ?? 0);
        if ($price <= '0.01') {
            return self::error_return('价格必须大于0');
        }
        if ($price >= $order['order_pay_price']) {
            return self::error_return('价格必须小于应付金额');
        }
        $res = (new Order())->data_update(['order_id' => $order_id], [
            'order_pay_price' => $price,
            'admin_reduce_price' => $order['order_pay_price'] - $price,//降低金额
        ]);
        if (!$res) {
            return self::error_return('修改价格失败');
        }
        OrderResult::add_order_log([
            'order_sn' => $order['order_sn'],
            'order_id' => $order['order_id'],
            'remark' => '修改' . $order['order_pay_price'] . '价格为：' . $price,
        ]);
        UserMsgResult::add($order['user_id'], [
            'title' => '订单价格修改',
            'content' => '订单号：' . $order['order_sn'] . '，订单价格修改为：' . $price . '，请尽快支付，否则订单将自动取消',
            'type' => 1,
            'path_info' => [
                'title' => '查看订单详情',
                'path' => '/pages/packageA/order/detail?order_sn=' . $order['order_sn'],
                'jump_type' => 'inner',//inner=内页，tab=底部导航，link=外链
            ]
        ]);
        return self::success_return('修改价格成功');
    }

    public function send($args): array
    {
        $order_id = intval($args['order_id'] ?? 0);
        $company_code = $args['company_code'] ?? '';
        $express_name = $args['express_name'] ?? '';
        $express_no = $args['express_no'] ?? '';
        $virtual_info = $args['virtual_info'] ?? '';
        if (!$order_id) {
            return self::error_return('参数错误');
        }

        $order = $this->model->data_get(['order_id' => $order_id], 'order_id,order_sn,order_status,order_goods_type')?->toArray();
        if (!$order) {
            return self::error_return('订单不存在');
        } elseif ($order['order_status'] != 1) {
            return self::error_return('订单状态不支持发货');
        }
        if ($order['order_goods_type'] == 1) {
            if (!$express_name || !$express_no) {
                return self::error_return('请填写快递信息');
            }
        } elseif ($order['order_goods_type'] == 2 && !$virtual_info) {
            return self::error_return('请填写虚拟商品发货内容');
        }

        Db::startTrans();
        try {
            if ($order['order_goods_type'] === 1) {
                $baseData = [
                    'order_id' => $order_id,
                    'order_sn' => $order['order_sn'],
                    'company_code' => $company_code,
                    'express_name' => $express_name,
                    'express_no' => $express_no,
                ];
                $res = (new OrderExpress())->data_add($baseData);
                if (!$res) {
                    throw new \Exception('保存物流信息失败');
                }
            }
            $res = (new Order())->data_update(['order_id' => $order_id], [
                'order_status' => 2,
                'send_time' => date('Y-m-d H:i:s'),
                'virtual_info' => $virtual_info,
            ]);
            if (!$res) {
                throw new \Exception('更新订单状态失败');
            }
            OrderResult::add_order_log([
                'order_sn' => $order['order_sn'],
                'order_id' => $order_id,
                'remark' => '订单发货',
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            return self::error_return('保存失败：' . $e->getMessage());
        }
        Db::commit();

        return self::success_return('保存成功', $args);
    }

    public function refund_save($args)
    {
        $order_id = intval($args['order_id'] ?? 0);
        $status = intval($args['status'] ?? 0);
        $to_type = $args['to_type'] ?? '';
        $check_fail_reason = $args['check_fail_reason'] ?? '';
        $id = intval($args['id'] ?? 0);
        if (!$id) {
            return self::error_return('参数错误');
        }
        if (!$order_id) {
            return self::error_return('请选择订单');
        }
        if (!$status) {
            return self::error_return('请选择退款结果');
        }
        if ($status == 1 && !$to_type) {
            return self::error_return('请选择退款到账方式');
        } else if ($status == -1 && !$check_fail_reason) {
            return self::error_return('请填写驳回理由');
        }
        $order = $this->model->data_get(['order_id' => $order_id], 'user_id,order_id,order_sn,order_status,order_pay_price,pay_type,pay_price');
        if (!$order) {
            return self::error_return('订单不存在');
        } elseif ($order['order_status'] != 5) {
            return self::error_return('订单状态不支持退款');
        }
        $log = (new OrderRefund())->data_get(['order_id' => $order_id, 'id' => $id]);
        if (!$log) {
            return self::error_return('退款记录不存在');
        } elseif ($log['status'] != 0) {
            return self::error_return('退款记录状态不支持修改');
        }
        Db::startTrans();
        try {
            //驳回时保持订单状态不变
            if ($status == 1) {
                $upOrder = ['order_status' => 6, 'cancel_time' => date('Y-m-d H:i:s')];

            } else {
                $upOrder = ['order_status' => $log['order_status']];
            }
            $res = (new Order())->data_update(['order_id' => $order_id], $upOrder);
            if (!$res) {
                throw new \Exception('更新订单状态失败');
            }

            $res = (new OrderRefund())->data_update(['id' => $id], [
                'status' => $status,
                'to_type' => $status == 1 ? $to_type : '',
                'check_time' => date('Y-m-d H:i:s'),
                'check_fail_reason' => $status == -1 ? $check_fail_reason : '',
            ]);
            if (!$res) {
                throw new \Exception('更新退款记录失败');
            }
            $res = OrderResult::add_order_log([
                'order_sn' => $order['order_sn'],
                'order_id' => $order_id,
                'remark' => '退款' . ($status == 1 ? '成功' : ($status == -1 ? '驳回' : '审核')),
            ]);
            if (!$res) {
                throw new \Exception('保存订单日志失败');
            }
            if ($status == 1 && $to_type == '原路返回') {
                $refund = OrderService::do_refund($order, $log);
                if ($refund['code'] != 0) {
                    throw new \Exception($refund['msg']);
                }
            }
            UserMsgResult::add($log['user_id'], [
                'title' => $order['order_sn'] . '退款' . ($status == 1 ? '成功' : ($status == -1 ? '驳回' : '审核')),
                'content' => '订单号：' . $order['order_sn'] . '，退款申请处理结果：' . ($status == 1 ? $to_type : $check_fail_reason) . '，请查看订单详情',
                'type' => 1,
                'path_info' => [
                    'title' => '查看订单详情',
                    'path' => '/pages/packageA/order/detail?order_sn=' . $order['order_sn'],
                    'jump_type' => 'inner',//inner=内页，tab=底部导航，link=外链
                ]
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            return self::error_return($e->getMessage());
        }
        Db::commit();
        return self::success_return();
    }
}
